﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MicroLED_Detecter
{
    public class ArrayScan
    {
        public string NewScan_CreateFolder(int rowcount, int columncount)// 新扫描创建文件夹,创建本次扫描的信息和图片储存文件
        {
            // 创建本次扫描的信息和图片储存文件：
            string targetPath = @"data\scanImg";// 获取扫描图片存储文件夹的路径
            string[] subDirectories = Directory.GetDirectories(targetPath);// 获取目标路径下的所有文件夹
            Array.Sort(subDirectories, (x, y) => String.Compare(y, x));// 按照创建时间倒序排序
            // 删除创建时间最早的文件夹，保留创建时间最近的4个文件夹，加后面创建的一个就是一直保持5个文件
            for (int i = 4; i < subDirectories.Length; i++)
                Directory.Delete(subDirectories[i], true);
            string foldername = DateTime.Now.ToString("yyyy MM dd HH mm ss");//string foldername="Images"+ DateTime.Now.ToString("yyyyMMddHHmmss");
            string folderPath = Path.Combine(targetPath, foldername);// 在存储文件夹中创建名为 "Images+创建时间" 的文件夹
            Directory.CreateDirectory(folderPath);// 创建文件夹
            //创建本次扫描的TXT信息文件
            string txt_filepath = Path.Combine(folderPath, "data.txt");
            string txt_data = foldername + " " + rowcount.ToString() + " " + columncount.ToString();
            File.WriteAllText(txt_filepath, txt_data);

            return foldername;
        }
        public int IsExistInterruptionRecord() //是否存在上次中断
        {
            string interrupt_txt_path = @"data\scanImg\interrupt.txt";
            string data = File.ReadAllText(interrupt_txt_path);// 读取中断信息文件
            // 将数据按照空格分割，并存储到对应的字符串变量中
            string[] data_parts = data.Split(',');
            string data_1 = data_parts[0];// scaninterrupt_row、scaninterrupt_column
            if (data_1 == "0 0")
                return 0;
            else
                return 1;
        }
        public int GetScanInterrupt_row() // 获取scaninterrupt_row，上次中断最后扫描完成的那个芯片的行数
        {
            string interrupt_txt_path = @"data\scanImg\interrupt.txt";
            string data = File.ReadAllText(interrupt_txt_path);// 读取中断信息文件
            // 将数据按照空格分割，并存储到对应的字符串变量中
            string[] data_parts = data.Split(',');
            string data_1 = data_parts[0];// scaninterrupt_row、scaninterrupt_column

            string[] data_1_parts = data_1.Split(' ');
            string str_scaninterrupt_row = data_1_parts[0];
            int scaninterrupt_row = int.Parse(str_scaninterrupt_row);
            return scaninterrupt_row;
        }
        public int GetScanInterrupt_column() // 获取scaninterrupt_column，上次中断最后扫描完成的那个芯片的列数
        {
            string interrupt_txt_path = @"data\scanImg\interrupt.txt";
            string data = File.ReadAllText(interrupt_txt_path);// 读取中断信息文件
            // 将数据按照空格分割，并存储到对应的字符串变量中
            string[] data_parts = data.Split(',');
            string data_1 = data_parts[0];// scaninterrupt_row、scaninterrupt_column

            string[] data_1_parts = data_1.Split(' ');
            string str_scaninterrupt_column = data_1_parts[1];
            int scaninterrupt_column = int.Parse(str_scaninterrupt_column);
            return scaninterrupt_column;
        }
        public string GetInterruptionFoldername()// 获取上次中断的图像保存文件
        {
            string interrupt_txt_path = @"data\scanImg\interrupt.txt";
            string data = File.ReadAllText(interrupt_txt_path);// 读取中断信息文件
            // 将数据按照空格分割，并存储到对应的字符串变量中
            string[] data_parts = data.Split(',');
            string data_2 = data_parts[1];// foldername
            return data_2;
        }
        public int GetRowcount() // 获取上次中断的预设的扫描行数
        {
            string interrupt_txt_path = @"data\scanImg\interrupt.txt";
            string data = File.ReadAllText(interrupt_txt_path);// 读取中断信息文件
            // 将数据按照空格分割，并存储到对应的字符串变量中
            string[] data_parts = data.Split(',');
            string data_3 = data_parts[2];// rowcount、columncount

            string[] data_3_parts = data_3.Split(' ');
            string str_rowcount = data_3_parts[0];
            int rowcount = int.Parse(str_rowcount);
            return rowcount;
        }
        public int GetColumncount() // 获取上次中断的预设的扫描列数
        {
            string interrupt_txt_path = @"data\scanImg\interrupt.txt";
            string data = File.ReadAllText(interrupt_txt_path);// 读取中断信息文件
            // 将数据按照空格分割，并存储到对应的字符串变量中
            string[] data_parts = data.Split(',');
            string data_3 = data_parts[2];// rowcount、columncount

            string[] data_3_parts = data_3.Split(' ');
            string str_columncount = data_3_parts[1];
            int columncount = int.Parse(str_columncount);
            return columncount;
        }    
        
        public int GetNewRoworColumn(int scaninterrupt_row, int scaninterrupt_column, int columncount ,int i)
        {
            int new_row = 1;
            int new_column = 1;
            if (scaninterrupt_row % 2 == 0)
            {
                new_row = scaninterrupt_row;
                new_column = (columncount + 1 - scaninterrupt_column) + 1;
            }
            else
            {
                new_row = scaninterrupt_row;
                new_column = scaninterrupt_column + 1;
            }
            if(i == 0)
                return new_row;
            else
                return new_column;
        }

        public int GetPythonFeedback(int i)
        {
            double feedback_dx_var = 0;
            double feedback_dy_var = 0;
            int feedback_dx = 0;
            int feedback_dy = 0;

            // 运行python反馈程序
            string exePath_Channel3 = @"scan_feedback\scan_feedback.exe"; // 运行python编好的图像处理程序-反馈系统
            Process process_Channel3 = new Process();
            process_Channel3.StartInfo.FileName = exePath_Channel3;
            try
            {
                process_Channel3.Start();
                process_Channel3.WaitForExit(); // 等待进程执行完成
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行错误：scan_feedback.exe：" + ex.Message);
                return 6;// python执行失误代码6
            }

            // 读取反馈值
            using (StreamReader reader = new StreamReader("data/Tempimg/feedback.txt"))//读取图片中心坐标
            {
                string content = reader.ReadToEnd();// 读取文件内容                       
                string[] numbers = content.Split(' ');// 将内容按空格分割为字符串数组

                // 将字符串转换为整数并存入变量
                feedback_dx_var = double.Parse(numbers[0]);
                feedback_dy_var = double.Parse(numbers[1]);
                // 四舍五入成整数
                feedback_dx = (int)Math.Round(feedback_dx_var);
                feedback_dy = (int)Math.Round(feedback_dy_var);
                // 设反馈上限，筛除误差过大的不正常反馈
                if (feedback_dx >= 3.0)
                    feedback_dx = 2;
                if (feedback_dx <= -3.0)
                    feedback_dx = -2;
                if (feedback_dy >= 3.0)
                    feedback_dy = 2;
                if (feedback_dy <= -3.0)
                    feedback_dy = -2;

                if (i == 0)
                    return feedback_dx;
                else 
                    return feedback_dy;
            }
        }

        public int RunPythonDetection()// 运行python检测程序
        {           
            string exePath_detection = @"scan_detect\scan_detect.exe"; // 运行python编好的图像处理程序-检测系统
            Process process_detection = new Process();
            process_detection.StartInfo.FileName = exePath_detection;
            try
            {
                process_detection.Start();
                process_detection.WaitForExit(); // 等待进程执行完成
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行错误：scan_detect.exe：" + ex.Message);
                return 6;
            }

            return 0;
        }
    }
}
